/*
 * 管理界面搜索框
 **/

import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Form, Button, Input, Select } from 'antd';

import cls from 'classnames';
import {
  SearchOutlined,
  ReloadOutlined,
  FilterOutlined,
} from '@ant-design/icons';
import { SearchBoxAPI } from '@/components/SearchBox/type';
import RangePicker from '@/components/RangePicker';
import _ from 'lodash';
import './styles.less';

const Index = React.forwardRef(
  (
    {
      switchList,
      onSwitch,
      searchList,
      onSearch,
      onReset,
    }: SearchBoxAPI.ISearchBox,
    ref: any,
  ) => {
    const [form] = Form.useForm();

    const [switchOpt, setSwitch] = useState<{
      key?: any;
      params?: Record<string, any>;
    }>({
      key: '',
      params: {},
    }); //选中的头部切换key值

    useEffect(() => {
      setSwitch({}); //初始设为空
      initialSwitch();
    }, []);

    /* ref 拿到当前组件的方法以及其他数据 */
    React.useImperativeHandle(ref, () => ({
      getRequest: () => {
        // 拿去当前组件的请求参数方法
        let values = form.getFieldsValue();
        let searchValues = screenValues(values);
        return {
          ...switchOpt?.params,
          ...searchValues,
        };
      },
    }));

    /*获取初始头部选中的选项*/
    const initialSwitch = () => {
      for (let i = 0; i <= switchList?.length; i++) {
        let item = switchList[i];
        if (item?.visible) {
          onColClick(item?.key, item?.params);
          return;
        }
      }
    };

    /* 点击切换 */
    const onColClick = (
      key: SearchBoxAPI.ISwitchKey,
      params?: Record<string, any>,
    ) => {
      if (key) {
        let searchValues = screenValues(form.getFieldsValue());
        onSwitch(key, searchValues, params); //切换方法
        setSwitch({
          key: key,
          params: params,
        });
      } else {
        return;
      }
    };

    /* 筛选搜索需要的值 */
    const screenValues = (values: any) => {
      let newValues: any = {};
      if (values) {
        Object?.keys(values).forEach((item) => {
          if (values?.[item]) {
            newValues[item] = values?.[item];
          }
        });
      }

      return newValues;
    };

    /* 表单组件渲染 */
    const getItemCom = (type: string, opt: SearchBoxAPI.ISearchList) => {
      switch (type) {
        case 'Input':
          return (
            <Input
              placeholder={opt?.placeholder}
              allowClear={opt?.allowClear}
            />
          );
        case 'Select':
          return (
            <Select placeholder={opt?.placeholder} allowClear={opt?.allowClear}>
              {opt?.dataSource &&
                opt?.dataSource?.map((item) => {
                  return (
                    <Select.Option key={item?.value} value={item?.value}>
                      {item?.name}
                    </Select.Option>
                  );
                })}
            </Select>
          );
        case 'RangePicker':
          return <RangePicker name={opt?.placeholder} />;
        default:
          return '';
      }
    };

    /* 查询点击时间 onSearchClick */
    const onSearchClick = () => {
      let FormValues = _.cloneDeep(form.getFieldsValue());
      let searchValue = screenValues(FormValues);
      if (onSearch) {
        onSearch({
          ...searchValue,
          ...switchOpt?.params,
        });
      }
    };

    /* 重置刷新点击事件 */
    const onResetClick = () => {
      form.resetFields();
      if (onReset) {
        onReset({
          ...switchOpt?.params,
        });
      }
    };

    return (
      <Card className={cls('search-box')} bordered={true}>
        {switchList && switchList?.length > 0 && (
          <Row className={cls('search-box-switch')}>
            {switchList.map((item) => {
              if (item?.visible) {
                let target = item?.key === switchOpt?.key;
                return (
                  <Col
                    md={item?.md ?? 2}
                    sm={item?.sm ?? 24}
                    style={{ ...item?.colStyle, marginRight: 10 }}
                    className={
                      item?.className ??
                      (target ? cls('switch-font-target') : cls('switch-font'))
                    }
                    key={item?.key}
                    onClick={() => {
                      onColClick(item?.key, item?.params);
                    }}
                  >
                    {item?.title}
                  </Col>
                );
              } else {
                return;
              }
            })}
          </Row>
        )}
        <div className={cls('search-box-form-layout')}>
          <div className={cls('search-box-form')}>
            <Form form={form} layout={'inline'}>
              <Row style={{ width: '100%' }} gutter={[16, 16]}>
                {searchList &&
                  searchList?.map((item) => {
                    return (
                      <Col
                        md={item?.md ?? 4}
                        sm={item?.sm ?? 24}
                        key={item?.name}
                      >
                        <Form.Item
                          style={{ ...item?.itemStyle }}
                          name={item?.name}
                        >
                          {item?.component
                            ? item.component
                            : getItemCom(item?.componentType, item)}
                        </Form.Item>
                      </Col>
                    );
                  })}
              </Row>
            </Form>
          </div>
          <div className={cls('search-box-btn')}>
            <Button
              type={'primary'}
              icon={<SearchOutlined />}
              onClick={onSearchClick}
            >
              查询
            </Button>

            <Button
              type={'default'}
              icon={<ReloadOutlined />}
              onClick={onResetClick}
            >
              重置
            </Button>

            <Button
              type={'default'}
              icon={<FilterOutlined />}
              id={cls('filter-btn')}
            >
              高级筛选
            </Button>
          </div>
        </div>
      </Card>
    );
  },
);

export default Index;
